<template>
  <div class="server-monitor">
    <!-- 刷新按钮 -->
    <el-card class="refresh-card">
      <div class="refresh-bar">
        <span class="title">服务器监控</span>
        <div class="refresh-actions">
          <el-switch
            v-model="autoRefresh"
            active-text="自动刷新"
            @change="toggleAutoRefresh"
          />
          <el-button type="primary" icon="Refresh" @click="getServerInfo">
            刷新
          </el-button>
        </div>
      </div>
    </el-card>

    <!-- 系统信息 -->
    <el-row :gutter="20">
      <!-- CPU信息 -->
      <el-col :xs="24" :sm="12" :lg="6">
        <el-card class="info-card">
          <template #header>
            <div class="card-header">
              <el-icon class="icon"><cpu /></el-icon>
              <span>CPU</span>
            </div>
          </template>
          <div v-loading="loading" class="info-content">
            <div class="progress-container">
              <el-progress
                type="circle"
                :percentage="serverInfo.cpu?.used || 0"
                :color="getProgressColor(serverInfo.cpu?.used || 0)"
                :width="120"
              >
                <template #default="{ percentage }">
                  <span class="percentage-text">{{ percentage.toFixed(1) }}%</span>
                </template>
              </el-progress>
            </div>
            <div class="details">
              <div class="detail-item">
                <span class="label">核心数:</span>
                <span class="value">{{ serverInfo.cpu?.cpuNum || 'N/A' }}</span>
              </div>
              <div class="detail-item">
                <span class="label">系统使用率:</span>
                <span class="value">{{ (serverInfo.cpu?.sys || 0).toFixed(2) }}%</span>
              </div>
              <div class="detail-item">
                <span class="label">负载:</span>
                <span class="value">{{ (serverInfo.cpu?.loadAverage || 0).toFixed(2) }}</span>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>

      <!-- 内存信息 -->
      <el-col :xs="24" :sm="12" :lg="6">
        <el-card class="info-card">
          <template #header>
            <div class="card-header">
              <el-icon class="icon"><monitor /></el-icon>
              <span>内存</span>
            </div>
          </template>
          <div v-loading="loading" class="info-content">
            <div class="progress-container">
              <el-progress
                type="circle"
                :percentage="serverInfo.memory?.usage || 0"
                :color="getProgressColor(serverInfo.memory?.usage || 0)"
                :width="120"
              >
                <template #default="{ percentage }">
                  <span class="percentage-text">{{ percentage.toFixed(1) }}%</span>
                </template>
              </el-progress>
            </div>
            <div class="details">
              <div class="detail-item">
                <span class="label">总内存:</span>
                <span class="value">{{ serverInfo.memory?.total || 'N/A' }}</span>
              </div>
              <div class="detail-item">
                <span class="label">已用:</span>
                <span class="value">{{ serverInfo.memory?.used || 'N/A' }}</span>
              </div>
              <div class="detail-item">
                <span class="label">可用:</span>
                <span class="value">{{ serverInfo.memory?.free || 'N/A' }}</span>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>

      <!-- JVM堆内存 -->
      <el-col :xs="24" :sm="12" :lg="6">
        <el-card class="info-card">
          <template #header>
            <div class="card-header">
              <el-icon class="icon"><data-analysis /></el-icon>
              <span>JVM堆内存</span>
            </div>
          </template>
          <div v-loading="loading" class="info-content">
            <div class="progress-container">
              <el-progress
                type="circle"
                :percentage="serverInfo.jvm?.heap?.usage || 0"
                :color="getProgressColor(serverInfo.jvm?.heap?.usage || 0)"
                :width="120"
              >
                <template #default="{ percentage }">
                  <span class="percentage-text">{{ percentage.toFixed(1) }}%</span>
                </template>
              </el-progress>
            </div>
            <div class="details">
              <div class="detail-item">
                <span class="label">最大:</span>
                <span class="value">{{ serverInfo.jvm?.heap?.max || 'N/A' }}</span>
              </div>
              <div class="detail-item">
                <span class="label">已用:</span>
                <span class="value">{{ serverInfo.jvm?.heap?.used || 'N/A' }}</span>
              </div>
              <div class="detail-item">
                <span class="label">已提交:</span>
                <span class="value">{{ serverInfo.jvm?.heap?.committed || 'N/A' }}</span>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>

      <!-- 磁盘信息 -->
      <el-col :xs="24" :sm="12" :lg="6">
        <el-card class="info-card">
          <template #header>
            <div class="card-header">
              <el-icon class="icon"><folder /></el-icon>
              <span>磁盘</span>
            </div>
          </template>
          <div v-loading="loading" class="info-content">
            <div class="progress-container">
              <el-progress
                type="circle"
                :percentage="serverInfo.disk?.usage || 0"
                :color="getProgressColor(serverInfo.disk?.usage || 0)"
                :width="120"
              >
                <template #default="{ percentage }">
                  <span class="percentage-text">{{ percentage.toFixed(1) }}%</span>
                </template>
              </el-progress>
            </div>
            <div class="details">
              <div class="detail-item">
                <span class="label">总空间:</span>
                <span class="value">{{ serverInfo.disk?.total || 'N/A' }}</span>
              </div>
              <div class="detail-item">
                <span class="label">已用:</span>
                <span class="value">{{ serverInfo.disk?.used || 'N/A' }}</span>
              </div>
              <div class="detail-item">
                <span class="label">可用:</span>
                <span class="value">{{ serverInfo.disk?.free || 'N/A' }}</span>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 详细信息 -->
    <el-row :gutter="20" style="margin-top: 20px">
      <!-- JVM信息 -->
      <el-col :xs="24" :lg="12">
        <el-card class="detail-card">
          <template #header>
            <div class="card-header">
              <el-icon class="icon"><set-up /></el-icon>
              <span>JVM信息</span>
            </div>
          </template>
          <div v-loading="loading" class="detail-content">
            <el-descriptions :column="1" border>
              <el-descriptions-item label="Java版本">
                {{ serverInfo.jvm?.version || 'N/A' }}
              </el-descriptions-item>
              <el-descriptions-item label="JVM名称">
                {{ serverInfo.jvm?.name || 'N/A' }}
              </el-descriptions-item>
              <el-descriptions-item label="供应商">
                {{ serverInfo.jvm?.vendor || 'N/A' }}
              </el-descriptions-item>
              <el-descriptions-item label="运行时间">
                {{ formatUptime(serverInfo.jvm?.uptime) }}
              </el-descriptions-item>
              <el-descriptions-item label="启动时间">
                {{ formatTimestamp(serverInfo.jvm?.startTime) }}
              </el-descriptions-item>
              <el-descriptions-item label="线程总数">
                {{ serverInfo.jvm?.thread?.total || 'N/A' }}
              </el-descriptions-item>
              <el-descriptions-item label="守护线程">
                {{ serverInfo.jvm?.thread?.daemon || 'N/A' }}
              </el-descriptions-item>
              <el-descriptions-item label="峰值线程">
                {{ serverInfo.jvm?.thread?.peak || 'N/A' }}
              </el-descriptions-item>
              <el-descriptions-item label="GC次数">
                {{ serverInfo.jvm?.gc?.totalCount || 'N/A' }}
              </el-descriptions-item>
              <el-descriptions-item label="GC时间">
                {{ serverInfo.jvm?.gc?.totalTime || 'N/A' }}ms
              </el-descriptions-item>
            </el-descriptions>
          </div>
        </el-card>
      </el-col>

      <!-- 系统信息 -->
      <el-col :xs="24" :lg="12">
        <el-card class="detail-card">
          <template #header>
            <div class="card-header">
              <el-icon class="icon"><platform /></el-icon>
              <span>系统信息</span>
            </div>
          </template>
          <div v-loading="loading" class="detail-content">
            <el-descriptions :column="1" border>
              <el-descriptions-item label="操作系统">
                {{ serverInfo.system?.osName || 'N/A' }}
              </el-descriptions-item>
              <el-descriptions-item label="系统架构">
                {{ serverInfo.system?.osArch || 'N/A' }}
              </el-descriptions-item>
              <el-descriptions-item label="系统版本">
                {{ serverInfo.system?.osVersion || 'N/A' }}
              </el-descriptions-item>
              <el-descriptions-item label="Java版本">
                {{ serverInfo.system?.javaVersion || 'N/A' }}
              </el-descriptions-item>
              <el-descriptions-item label="Java供应商">
                {{ serverInfo.system?.javaVendor || 'N/A' }}
              </el-descriptions-item>
              <el-descriptions-item label="Java路径">
                {{ serverInfo.system?.javaHome || 'N/A' }}
              </el-descriptions-item>
              <el-descriptions-item label="用户名">
                {{ serverInfo.system?.userName || 'N/A' }}
              </el-descriptions-item>
              <el-descriptions-item label="用户目录">
                {{ serverInfo.system?.userDir || 'N/A' }}
              </el-descriptions-item>
              <el-descriptions-item label="时区">
                {{ serverInfo.system?.userTimezone || 'N/A' }}
              </el-descriptions-item>
            </el-descriptions>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, onUnmounted } from 'vue'
import { ElMessage } from 'element-plus'
import { getServerInfo } from '@/api/monitor/server'

// 响应式数据
const loading = ref(false)
const autoRefresh = ref(false)
const serverInfo = reactive<any>({})
let refreshTimer: NodeJS.Timeout | null = null

/** 获取服务器信息 */
const fetchServerInfo = async () => {
  loading.value = true
  try {
    const { data } = await getServerInfo()
    Object.assign(serverInfo, data)
  } catch (error) {
    console.error('获取服务器信息失败:', error)
    ElMessage.error('获取服务器信息失败')
  } finally {
    loading.value = false
  }
}

/** 手动刷新 */
const handleRefresh = () => {
  fetchServerInfo()
}

/** 切换自动刷新 */
const toggleAutoRefresh = (value: boolean) => {
  if (value) {
    startAutoRefresh()
  } else {
    stopAutoRefresh()
  }
}

/** 开始自动刷新 */
const startAutoRefresh = () => {
  refreshTimer = setInterval(() => {
    fetchServerInfo()
  }, 5000) // 每5秒刷新一次
}

/** 停止自动刷新 */
const stopAutoRefresh = () => {
  if (refreshTimer) {
    clearInterval(refreshTimer)
    refreshTimer = null
  }
}

/** 获取进度条颜色 */
const getProgressColor = (percentage: number) => {
  if (percentage < 50) return '#67c23a'
  if (percentage < 80) return '#e6a23c'
  return '#f56c6c'
}

/** 格式化运行时间 */
const formatUptime = (uptime: number) => {
  if (!uptime) return 'N/A'
  
  const seconds = Math.floor(uptime / 1000)
  const days = Math.floor(seconds / 86400)
  const hours = Math.floor((seconds % 86400) / 3600)
  const minutes = Math.floor((seconds % 3600) / 60)
  
  return `${days}天${hours}小时${minutes}分钟`
}

/** 格式化时间戳 */
const formatTimestamp = (timestamp: number) => {
  if (!timestamp) return 'N/A'
  return new Date(timestamp).toLocaleString()
}

// 生命周期
onMounted(() => {
  fetchServerInfo()
})

onUnmounted(() => {
  stopAutoRefresh()
})
</script>

<style lang="scss" scoped>
.server-monitor {
  padding: 20px;
}

.refresh-card {
  margin-bottom: 20px;
  
  .refresh-bar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    
    .title {
      font-size: 18px;
      font-weight: 600;
      color: var(--el-text-color-primary);
    }
    
    .refresh-actions {
      display: flex;
      align-items: center;
      gap: 16px;
    }
  }
}

.info-card {
  height: 280px;
  
  .card-header {
    display: flex;
    align-items: center;
    gap: 8px;
    
    .icon {
      font-size: 20px;
      color: var(--el-color-primary);
    }
  }
  
  .info-content {
    height: 200px;
    display: flex;
    flex-direction: column;
    align-items: center;
    
    .progress-container {
      margin-bottom: 20px;
      
      .percentage-text {
        font-size: 14px;
        font-weight: 600;
      }
    }
    
    .details {
      width: 100%;
      
      .detail-item {
        display: flex;
        justify-content: space-between;
        margin-bottom: 8px;
        
        .label {
          color: var(--el-text-color-regular);
          font-size: 12px;
        }
        
        .value {
          color: var(--el-text-color-primary);
          font-size: 12px;
          font-weight: 500;
        }
      }
    }
  }
}

.detail-card {
  .card-header {
    display: flex;
    align-items: center;
    gap: 8px;
    
    .icon {
      font-size: 20px;
      color: var(--el-color-primary);
    }
  }
  
  .detail-content {
    :deep(.el-descriptions) {
      .el-descriptions__label {
        width: 120px;
        background-color: var(--el-fill-color-lighter);
      }
      
      .el-descriptions__content {
        word-break: break-all;
      }
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .server-monitor {
    padding: 10px;
  }
  
  .refresh-bar {
    flex-direction: column;
    gap: 16px;
    
    .refresh-actions {
      width: 100%;
      justify-content: center;
    }
  }
  
  .info-card {
    height: auto;
    margin-bottom: 20px;
  }
}
</style>

